<?php

namespace App\Services;

use App\Models\Cms_Match;
use App\Traits\External;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class MatchService
{
    public function matchList($params)
    {
        $result = Cms_Match::getFilter($params)
            ->Nodel()
            ->paginate($params['pageSize']);
        $list['total'] = $result->total();
        $result = External::optionResultSingle($result,2);
        $list['list'] = $result;
        return $list;
    }

    public function matchAdd($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();
            $params['create_time'] = Carbon::now()->timestamp;
            $params['update_time'] = Carbon::now()->timestamp;
            $res = Cms_Match::where('mid', $params['mid'])
                ->where('otherid', $params['otherid'])
                ->first();
            if(!empty($res))
            {
                $res->is_del = 0;
                $res->maker_id = $params['maker_id'];
                $res->update_time = Carbon::now()->timestamp;
                if(!$res->save()){
                    throw new \Exception("更新Cms_Match失败".$params['id']);
                }
            }else{
                $result = Cms_Match::create($params);
                if(!$result){
                    throw new \Exception("新增Cms_Match失败".$params['id']);
                }
            }



            DB::commit();
            return true;
        }catch (\Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }

    public function matchDel($params)
    {
        try {
            // 开始数据库事务
            DB::beginTransaction();

            $res = Cms_Match::find($params['id']);
            $res->is_del = 1;
            if(!$res->save()){
                throw new \Exception("删除Cms_Match失败".$params['id']);
            }

            DB::commit();
            return true;
        }catch (\Throwable $e) {
            // 如果在事务执行过程中发生异常，则回滚事务
            DB::rollBack();
            // 记录日志或处理错误
            Log::error("Database transaction failed: " . $e->getMessage());
            return false;
        }
    }


}
